package com.ccteam.fluidmusic.ui.auth

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import cn.hutool.core.lang.Validator
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentLoginVerificationBinding
import com.ccteam.fluidmusic.utils.EventObserver
import com.ccteam.fluidmusic.utils.VerifyCodeCountDownTimer
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.fluidmusic.widget.SNACKBAR_ALL_BOTTOM_BAR
import com.ccteam.fluidmusic.widget.SNACKBAR_BOTTOM
import com.ccteam.fluidmusic.widget.snackbar
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author Xiaoc
 * @since 2021/3/29
 *
 * 以验证码形式登录界面Fragment
 */
@AndroidEntryPoint
class LoginVerificationFragment: Fragment() {

    private var _binding: FragmentLoginVerificationBinding? = null
    private val binding get() = _binding!!

    private val loginVerificationViewModel by viewModels<LoginVerificationViewModel>()

    private val verifyCodeCountDownTimer = VerifyCodeCountDownTimer()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentLoginVerificationBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        binding.toolbarLogin.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        viewLifecycleOwner.lifecycleScope.launch {
            verifyCodeCountDownTimer.countDown.collectLatest {
                if(it is VerifyCodeCountDownTimer.Status.Timing){
                    updateTiming(it.currentCountDownNum)
                } else {
                    updateNotTiming()
                }
            }
        }

        /**
         * 观察是否开启获取验证码按钮
         */
        loginVerificationViewModel.enableVerifyCodeButton.observe(viewLifecycleOwner, {
            binding.btnVerify.isEnabled = it && verifyCodeCountDownTimer.countDown.value !is VerifyCodeCountDownTimer.Status.Timing
        })

        loginVerificationViewModel.enableCountDown.observe(viewLifecycleOwner,EventObserver{
            if(it){
                verifyCodeCountDownTimer.start()
            }
        })

        /**
         * 观察登录加载情况
         * 并在不同情况下加载不同UI
         */
        loginVerificationViewModel.loadMessage.observe(viewLifecycleOwner, EventObserver {
            binding.btnLogin.setLoading(it is LoadMessage.Loading)
            if(it is LoadMessage.Error){
                view.snackbar(it.errorMessage.description.toString(), SNACKBAR_BOTTOM).show()
            } else if(it is LoadMessage.NotLoading){
                view.snackbar(R.string.description_success_login, SNACKBAR_ALL_BOTTOM_BAR).show()
                findNavController().navigateUp()
            }
        })

        /**
         * 观察是否开启登录按钮
         */
        loginVerificationViewModel.enableLoginButton.observe(viewLifecycleOwner, {
            binding.btnLogin.isEnabled = it
        })

        /**
         * 观察电话号码输入框，实时检测电话号码合法性
         */
        binding.editAccount.addOnEditTextAttachedListener { inputLayout ->
            inputLayout.editText?.doOnTextChanged { text, _,_,_ ->
                val isMobile = Validator.isMobile(text.toString())
                loginVerificationViewModel.setPhone(text.toString())
                loginVerificationViewModel.setEnableVerify(isMobile)
                loginVerificationViewModel.setPhoneSuccess(isMobile)
            }
        }

        binding.editVerifyCode.addOnEditTextAttachedListener { inputLayout ->
            inputLayout.editText?.doOnTextChanged { text, _, _, _ ->
                loginVerificationViewModel.setVerifySuccess(text.toString().isNotEmpty())
            }
        }

        binding.btnVerify.setProgressButtonOnClickListener {
            loginVerificationViewModel.getVerification()
        }

        binding.btnLogin.setProgressButtonOnClickListener {
            loginVerificationViewModel.loginVerification(
                binding.editVerifyCode.editText?.text.toString()
            )
        }
    }

    private fun updateTiming(countDownNum: Int){
        binding.btnVerify.isEnabled = false
        binding.btnVerify.text = countDownNum.toString()
    }

    private fun updateNotTiming(){
        binding.btnVerify.isEnabled = true && loginVerificationViewModel.enableVerifyCodeButton.value == true
        binding.btnVerify.text = getString(R.string.description_get_verification)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.editAccount.clearOnEditTextAttachedListeners()
        verifyCodeCountDownTimer.cancel()

        _binding = null
    }
}